import React, { useEffect, useReducer, useRef, useState } from 'react'
import {
  ic_upgrade,
  ic_arrow,
  ic_bed,
  ic_medicine,
  ic_phone,
  header_banner,
  header_bg,
  ic_ok,
  ic_ok_lg,
  ic_guide,
  ic_sm_hospital,
  ic_sm_medicine,
  ic_sm_operation,
  ic_md_medicine,
  ic_md_method,
  ic_md_ok,
  ic_answer,
  ic_question,
  ic_example_user,
  ic_service_phone,
  ic_step,
  ic_md_card,
  ic_md_heart,
  ic_add
} from '@/utils/loadImages'
import './index.scss'
import { Applicant, Insureds, InsureModal } from './components'
import { BaseUrl } from './common/constant'
import { API } from './common/api'
import { isValidIdCard, isValidName, isValidPhone } from '@/utils'
import { Toast } from 'antd-mobile'
import { useHistory } from 'react-router-dom'
import NoticeModal from './components/NoticeModal'
import Upgrade from '@/components/Upgrade'

let i = 1
let initInsureds = {
  name: '',
  idNo: '',
  mobile: '',
  relation: null,
  socialInsuFlag: null,
  accessorys: null
}

const RedCardRenewal = () => {
  const history = useHistory();
  const [isAgree, setIsAgree] = useState(false)
  const [applicant, setApplicant] = useReducer((oldValue, newValue) => {
    return { ...oldValue, ...newValue }
  }, {})
  const [insureds, setInsureds] = useState({
    [i]: initInsureds
  })
  const insureRef = useRef<any>()
  const noticeRef = useRef<any>()

  const isValidApplicant = () => {
    let isValid = true;

    if (!isValidName(applicant.name)) {
      isValid = false;
      Toast.fail('投保人姓名必须为2位以上非空字符', 2, undefined, false);
      return isValid;
    }

    if (!isValidIdCard(applicant.idNo)) {
      isValid = false;
      Toast.fail('投保人身份证格式不正确',  2, undefined, false);
      return isValid;
    }

    if (!isValidPhone(applicant.mobile)) {
      isValid = false;
      Toast.fail('投保人手机号格式不正确',  2, undefined, false)
      return isValid;
    }

    return true;
  }

  const isValidInsured = (insured, index) => {
    let isValid = true;

    if (!isValidName(insured.name)) {
      isValid = false;
      Toast.fail(`被投保人${index}姓名必须为2位以上非空字符`, 2, undefined, false);
      return isValid;
    }

    if (!isValidIdCard(insured.idNo)) {
      isValid = false;
      Toast.fail(`被投保人${index}身份证格式不正确`,  2, undefined, false);
      return isValid;
    }

    // if (!isValidPhone(insured.mobile)) {
    //   isValid = false;
    //   Toast.fail('被投保人手机号格式不正确',  2, undefined, false)
    //   return isValid;
    // }

    if (!insured.relation) {
      isValid = false;
      Toast.fail(`请选择被投保人${index}与投保人的关系`,  2, undefined, false)
      return isValid;
    }

    if (insured.socialInsuFlag !== true && insured.socialInsuFlag !== false) {
      isValid = false;
      Toast.fail(`请选择被保人${index}有无社保`,  2, undefined, false)
      return isValid;
    }

    return true;
  }

  const submit = async () => {
    let isValid = true;
    let length = Object.keys(insureds).length;

    if (!isValidApplicant()) {
      return false;
    }

    for (let i = 0; i < length; i++) {
      isValid = isValidInsured(Object.values(insureds)[i], i + 1);
      if (!isValid) {
        break;
      }
    }

    if (!isValid) {
      return false;
    }

    history.push('/redCardConfirm', {
      applicant,
      insurants: Object.values(insureds)
    })
  }

  useEffect(() => {
    noticeRef.current.toggle(true)
  }, [])

  return (
    <div className="red-card-page">
      <div className="body">
        <div
          className="header"
          style={{ background: `url(${header_bg}) 50% 0% / contain no-repeat` }}>
          <h2>惠军家庭医疗保险服务卡</h2>
          <h3>您为我们守护国家 我们为您守护小家</h3>
          <img src={header_banner} alt="" />
        </div>
        <div className="content">
          <div className="card">
            <div className="intro">
              <div className="intro_item">
                <img src={ic_md_heart} alt="" />
                <p>
                  最高600万
                  <br />
                  最大疾病医疗保障
                </p>
              </div>
              <div className="intro_split">+</div>
              <div className="intro_item">
                <img src={ic_md_medicine} alt="" />
                <p>
                  最高300万
                  <br />
                  一般医疗保障
                </p>
              </div>
              <div className="intro_split">+</div>
              <div className="intro_item">
                <img src={ic_md_card} alt="" />
                <p>
                  医疗垫付
                  <br />
                  重疾绿通
                </p>
              </div>
            </div>
          </div>

          <div className="card" id="applicant-form">
            <h2 className="section_title">投保人</h2>
            <Applicant applicant={applicant} setApplicant={setApplicant} />
          </div>

          {/* <div className="card">
            <h2 className="section_title">为谁投保</h2>
            <div className='relation'>
            <label onClick={() => setRelation('本人')} className={`${relation === '本人' ? 'active' : ''}`}>本人</label>
            <label onClick={() => setRelation('子女')} className={`${relation === '子女' ? 'active' : ''}`}>子女</label>
            <label onClick={() => setRelation('父母')} className={`${relation === '父母' ? 'active' : ''}`}>父母</label>
            <label onClick={() => setRelation('配偶')} className={`${relation === '配偶' ? 'active' : ''}`}>配偶</label>
            </div>
          </div> */}

          {Object.keys(insureds).map((key, index) => {
            return (
              <div className="card" key={key}>
                <h2 className="section_title">被保人{key}</h2>
                <Insureds insureds={insureds[key]} setInsureds={(param: Record<string, any>) => {
                  setInsureds({...(insureds || {}), ...(param || {})})
                }} index={key} />
              </div>
            )
          })}

          <div className="btn_groups">
            <div
              className="btn_add"
              onClick={() => {
                setInsureds({ ...insureds, [++i]: initInsureds })
              }}>
              <img src={ic_add} alt="" />
              添加被保险人
            </div>
            <div className="btn_ok" onClick={submit}>
              立即办理
            </div>
          </div>

          {/* 保障详情 */}
          <div className="card gradient">
            <h2 className="section_title">保障详情</h2>
            <table className="guaranteeDetails">
              <thead>
                <tr>
                <th>保险责任</th>
                <th>免赔额</th>
                <th>保障金额</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>一般医疗保险金</td>
                  <td>1万元</td>
                  <td>300万元</td>
                </tr>
                <tr>
                  <td>重大疾病医疗保险金</td>
                  <td rowSpan={5} style={{ verticalAlign: 'middle' }}>
                    0元
                  </td>
                  <td>300万元</td>
                </tr>
                <tr>
                  <td>恐性肿瘤质子重离子保险金</td>
                  <td>100万元</td>
                </tr>
                <tr>
                  <td>恶性肿瘤医疗住院津贴</td>
                  <td>18000元</td>
                </tr>
                <tr>
                  <td>重大疾病异地转诊公共交通保险金</td>
                  <td>5000元</td>
                </tr>
                <tr>
                  <td>恶性肿瘤特药保险金（同主险）</td>
                  <td>600万元</td>
                </tr>
                <tr>
                  <td>重大疾病一次性给付（5/10万）保险金</td>
                  <td>可选责任</td>
                  <td>5/10万元</td>
                </tr>
              </tbody>
            </table>

            {/* <div className="detail">
              <div className="detail_item">
                <span>一般医疗保险金</span>
                <span>300万</span>
              </div>
              <div className="detail_item">
                <span>重大疾病医疗保险金</span>
                <span>300万</span>
              </div>
              <div className="detail_item">
                <span>恶性肿瘤质子重离子保险金</span>
                <span>100万</span>
              </div>
              <div className="detail_item">
                <span>恶性肿瘤医疗住院津贴</span>
                <span>18000元</span>
              </div>
              <div className="detail_item">
                <span>重大疾病异地转诊公共交通费用</span>
                <span>5000元</span>
              </div>
              <div className="split"></div>
              <div className="detail_item">
                <span>恶性肿瘤特药保险金（同主险）</span>
                <span>600万</span>
              </div>
              <div className="detail_item">
                <span>重大疾病一次性给付金（ 5万/10万）</span>
                <span></span>
              </div>
              <div className="detail_item">
                <span>恶性肿瘤特需责任</span>
                <span></span>
              </div>
            </div> */}
          </div>

          <div className="agreement">
            <span
              className={`agreement_radio ${isAgree ? 'active' : ''}`}
              onClick={() => {
                setIsAgree(!isAgree)
              }}></span>
            <div className="agreement_text">
              我已查看<span onClick={() => {
                history.push('/viewer?name=InsuranceNotice')
              }}>《投保须知》</span>
              <span onClick={() => {
                history.push('/viewer?name=OccupationTable')
              }}>《特别职业表》</span>
              <span onClick={() => {
                history.push('/viewer?name=ExpensesClause')
              }}>《特需医疗费用条款》</span>
              <span onClick={() => {
                history.push('/viewer?name=SpecificDrugs')
              }}>《院外特定药品条款》</span>
              <span onClick={() => {
                history.push('/viewer?name=HealthNotification')
              }}>《健康告知》</span>
              <span onClick={() => {
                history.push('/viewer?name=InsuranceClause')
              }}>《重大疾病保险条款》</span>
            </div>
          </div>

          <Upgrade />

          {/* 产品亮点 */}
          <div className="card" style={{ paddingTop: '0' }}>
            <h2 className="card_title">产品亮点</h2>
            <div className="hightlights">
              <div className="hightlights_item">
                <img src={ic_md_medicine} alt="" />
                <p>不限疾病种类</p>
              </div>
              <div className="hightlights_item">
                <img src={ic_md_ok} alt="" />
                <p>不限用药种类</p>
              </div>
              <div className="hightlights_item">
                <img src={ic_md_method} alt="" />
                <p>不限治疗方式</p>
              </div>
            </div>

            <div className="hightlights_list">
              <div className="hightlights_list_item">
                <img src={ic_ok} alt="" />
                医疗费用报销比例100%
              </div>
              <div className="hightlights_list_item">
                <img src={ic_ok} alt="" />
                高额医疗费不用愁<span>可垫付</span>
              </div>
              <div className="hightlights_list_item">
                <img src={ic_ok} alt="" />
                专属理赔团队，报销时效有保障
              </div>
            </div>
          </div>

          {/* 前沿疗法 */}
          <div className="card" style={{ paddingTop: '0' }}>
            <h2 className="card_title">
              <img src={ic_upgrade} className="ic_upgrade" alt="" />
              <span>前沿疗法已纳入保障</span>
            </h2>
            <h3 className="title">
              <span style={{ color: '#FC8F2B' }}>120万</span>一针“癌症清零药”
            </h3>
            <h5 className="subtitle">已纳入保障中</h5>
            <div className="card_orange">
              <div className="card_orange_img">
                <img src={ic_arrow} alt="" />
              </div>
              <div className="card_orange_text">
                国际最先进的car-t细胞疗法，对急性淋巴细胞白血病、多发性骨髓瘤、慢性淋巴细胞白血病，以及部分实体肿瘤和一些骨髓系白血病有显著效果。
              </div>
            </div>
            <div className="card_blue">
              享受 car-t 细胞疗法
              <br />
              给自己一个 “免疫” 癌症的机会
            </div>

            <div className="effect">
              <div className="effect_item">
                <label>效果显著：</label>
                <p>一针即可清除体内癌细胞，可达到治愈效果。</p>
              </div>
              <div className="effect_item">
                <label>价格昂贵：</label>
                <p>120万元，让多数患者望尘莫及。</p>
              </div>
              <div className="effect_item">
                <label>无法报销：</label>
                <p>car-t细胞治疗药物未能进入医保目录，医保无法报销。</p>
              </div>
            </div>
          </div>

          <div className="card" style={{ paddingTop: '0' }}>
            <h2 className="card_title">报销不限疾病种类/治疗方式</h2>
            <div className="guarantee">
              <div>
                <img src={ic_ok} alt="" />
                <span>生病用好药</span>
              </div>
              <div>
                <img src={ic_ok} alt="" />
                <span>理赔范围广</span>
              </div>
            </div>
            <div className="btn_blue">新增百万特药保障</div>
            <table className="table">
              <tbody>
                <tr>
                  <td>
                    <img src={ic_sm_medicine} alt="" />
                    药品
                  </td>
                  <td>进口药、自费药、疾病、意外…</td>
                </tr>
                <tr>
                  <td>
                    <img src={ic_sm_operation} alt="" />
                    手术
                  </td>
                  <td>门诊、急诊、住院、门诊放疗、化疗…</td>
                </tr>
                <tr>
                  <td>
                    <img src={ic_sm_hospital} alt="" />
                    药品
                  </td>
                  <td>治疗费、检查费、ICU费用、护理费、床位费、加床费</td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 保障特色 */}
          <div className="card" style={{ paddingTop: '0' }}>
            <h2 className="card_title">保障特色</h2>
            <h3 className="title">全方位升级健康服务</h3>
            <div className="service">
              {['约号难', '排队难', '住院手术难', '医疗费用难'].map((item, index) => {
                return (
                  <div className="service_item" key={index}>
                    <img src={ic_ok_lg} alt="" />
                    <span>{item}</span>
                  </div>
                )
              })}
            </div>
            <div className="card_orange">
              <div className="card_orange_img">
                <img alt="" src={ic_guide} />
              </div>
              <div className="card_orange_text lg">
                三家央企承保，踏实放心
                <br />
                专属报销服务通道
                <br />
                全新健康服务升级
                <br />
                异地转诊交通费可报销
                <br />
                恶性肿瘤住院津贴
                <br />
              </div>
            </div>
            <div className="guide">
              <div className="guide_item">
                <img src={ic_phone} alt="" />
                <p className="guide_item_text">电话/视频问诊，重疾优先预约挂号。</p>
              </div>
              <div className="guide_item">
                <img src={ic_bed} alt="" />
                <p className="guide_item_text">
                  重疾住院协调，重疾手术协调，住院医疗垫付，住院津贴补助，异地转诊交通补助。
                </p>
              </div>
              <div className="guide_item">
                <img src={ic_medicine} alt="" />
                <p className="guide_item_text">用药指导，康复指导，专属理赔通道。</p>
              </div>
            </div>
          </div>

          {/* 报销案例 */}
          <div className="card" style={{ paddingTop: 0 }}>
            <h2 className="card_title">报销案例</h2>
            <img src={ic_example_user} alt="" className="example_user" />
            <div className="example">
              <img src={ic_step} className="example_step" alt="" />
              <div className="example_section">
                <h2>办理</h2>
                <p>张先⽣2023年1⽉，办理了《惠军家庭医疗保险服务卡》。</p>
                <h2>出险</h2>
                <p>
                  办理后的第二个月，张先生因<span style={{ color: '#FDB84D' }}>肝部恶性肿瘤</span>
                  住院治疗，化疗加手术治疗3个月，共花费275661.8元，其由社保报销124508.32自费151153.48元
                </p>
                <h2>报销</h2>
                <p>
                  由于张先生所患疾病为恶性肿瘤，属于重大疾病保险责任，张先生自费支出的151153.48元获得100%报销
                </p>
              </div>
            </div>
          </div>

          {/* 常见问题 */}
          <div className="card">
            <h2 className="section_title">常见问题</h2>
            <div className="questions">
              {[
                {
                  question: '发生风险时如何报销？',
                  answer:
                    '办理完住院手续，您需拨打中国人寿的客服热线95519进行报案出险，后续会有专项工作人员协同您处理报销事宜。'
                },
                {
                  question: '在哪些医院治疗，可以获得理赔？',
                  answer:
                    '中华⼈⺠共和国境内(港、澳、台地区除外)经中国卫⽣部⻔评审确定的⼆级或以上公⽴医院，但不包含其中的特需医疗、外宾医疗、⼲部病房。也不包括以下或类似医疗机构：<br/>1、精神病院，精神⼼理治疗中⼼；<br/>2、⽼⼈院、疗养院、戒毒中⼼或戒酒中⼼；<br/>3、健康中⼼或天然治疗所、疗养或康复院；<br/>4、⽆相应医护⼈员或设备的⼆级及以下的联合医院或联合病房。'
                },
                {
                  question: '所有的医院费用都可以报销吗？',
                  answer:
                    '对于保障范围内的医疗费⽤中，个⼈⽀付(含社保个⼈账户⽀付和现⾦⽀付)超过1万元的部分，⽆论是否属于医保范围，均可100%报销。'
                },
                {
                  question: '年免赔额1万元，怎么理解？',
                  answer: '免赔额类似于社保的起付线，(本保障约定的属于重大疾病范畴的0免赔额）'
                }
              ].map((item: any, index: number) => {
                return (
                  <div className="questions_item" key={index}>
                    <div className="question">
                      <img src={ic_question} alt="" />
                      <p>{item.question}</p>
                    </div>
                    <div className="answer">
                      <img src={ic_answer} alt="" />
                      <p dangerouslySetInnerHTML={{ __html: item.answer }}></p>
                    </div>
                  </div>
                )
              })}
            </div>
          </div>

          <div className="company">天彩保险经纪</div>
          <img className="service_phone" src={ic_service_phone} alt="" />
        </div>
      </div>

      <div className="footer">
        <div
          className="btn"
          onClick={async () => {
            // insureRef.current.toggle(true)
            if (!await submit()) {
              document.getElementById('applicant-form')?.scrollIntoView({behavior: 'smooth', block: 'start'})
            }
          }}>
          立即办理
        </div>
      </div>

      {/* <InsureModal ref={insureRef} /> */}
      <NoticeModal ref={noticeRef} />
    </div>
  )
}

export default RedCardRenewal
